// pages/device/atifyDeatil/atifyDeatil.js
import lwx from '../../../utils/lwx.js'
import {
  _globle
} from '../../../utils/globle.js'
import devices from '../../../utils/devices.js'

Page({
  _useId: 5,
  rand2: 0,
  rand1: 0,
  /**
   * 页面的初始数据
   */
  data: {
    detail: {},
    hiddenModal: true,
    textvalue: '',
    applyId: '',
    devicesId: '',
    devicesActId: '',
    title: '',
    items: [{
        name: '法务审批',
        value: 'useLegal',
        disabled: false
      },
      {
        name: '重大事项审批',
        value: 'useBigissues',
        disabled: false,
      },
    ],
    applyInfo: ["../../../images/add_photo.jpg"],
    useBigissues: 'N',
    useLegal: 'N',
    //法务
    iwLegalNames: [],
    //顺序
    processData: [],
    //重大事项
    bigissueg: [],
    //特批
    special: [],
    applyImageUrl: [],
    hechaImageUrl: [],
    phonePhotoUrls: [],
    isUsed: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    var that = this;
    var title = options.title;
    that.setData({
      title: options.title
    })
    wx.setNavigationBarTitle({
      title: title,
    })
    if (title == '待批准' || title == '已批准' || title == '已撤销') {
      that.setData({
        applyId: options.id,
      })
      that.loadDetail(options.id);
    } else if (title == '常规申请') {
      that.setData({
        applyId: options.applyId,
        applyVerifyId: options.applyVerifyId
      })
      that.loadData(options.applyId, options.applyVerifyId);
    } else if (title == '时段申请') {
      that.setData({
        applyId: options.applyId,
        applyVerifyId: options.applyVerifyId
      })
      that.loadData(options.applyId, options.applyVerifyId);
    } else if (title == '已拒绝') {
      that.setData({
        applyId: options.id,
      })
      that.loadJujueData(options.id);
    } else if (title == '待核查' || title == '已核查') {
      that.setData({
        devicesId: options.devicesId,
      })
      that.loadDaihechaData(options.devicesId, options.status);
    } else if (title == '法务审批') {
      var items = [{
        name: '重大事项审批',
        value: 'useBigissues',
        disabled: false,
      }, ]
      that.setData({
        applyId: options.applyId,
        applyVerifyId: options.applyVerifyId,
        items: items
      })
      that.loadData(options.applyId);
    } else if (title == '重大事项审批') {
      var items = []
      that.setData({
        applyId: options.applyId,
        applyVerifyId: options.applyVerifyId,
        items: items
      })
      that.loadData(options.applyId);
    }
  },
  // 重大事项审批勾选
  checkboxChange: function(e) {
    console.log(e)
    var useBigissues = 'N';
    var useLegal = 'N';
    for (var i = 0; i < e.detail.value.length; i++) {
      if (e.detail.value[i] == 'useBigissues') {
        useBigissues = 'Y';
      } else if (e.detail.value[i] == 'useLegal') {
        useLegal = 'Y';
      }
    }
    this.setData({
      useBigissues: useBigissues,
      useLegal: useLegal
    });
  },
  //同意
  agree: function() {
    var that = this;
    console.log('applyVerifyId=====' + that.data.applyVerifyId)
    // console.log(that.data.useLegal
    lwx.request({
      url: "verify.update",
      data: {
        applyVerifyId: that.data.applyVerifyId,
        verifyStatus: 'PASSED',
        useBigissues: that.data.useBigissues,
        useLegal: that.data.useLegal,
        partyId: _globle.user.partyId,
        companyId: _globle.user.companyId
      }
    }).then(res => {
      console.log(res)
      if (res.data.code == '0') {
        wx.showToast({
          title: '已同意',
        })
        setTimeout(function() {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  //拒绝
  refuse: function() {
    var that = this;
    lwx.request({
      url: "verify.update",
      data: {
        applyVerifyId: that.data.applyVerifyId,
        verifyStatus: 'REJECT',
        useBigissues: '',
        useLegal: '',
        partyId: _globle.user.partyId,
        companyId: _globle.user.companyId
      }
    }).then(res => {
      console.log(res)
      if (res.data.code == '0') {
        wx.showToast({
          title: '已拒绝',
        })
        setTimeout(function() {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  //法务审批决绝
  fawuRefuse: function() {
    var that = this;
    lwx.request({
      url: "egalStatus.update",
      data: {
        applyVerifyId: that.data.applyVerifyId,
        verifyStatus: 'REJECT',
        useBigissues: '',
        useLegal: '',
        partyId: _globle.user.partyId,
        companyId: _globle.user.companyId
      }
    }).then(res => {
      console.log(res)
      if (res.data.code == '0') {
        wx.showToast({
          title: '已拒绝',
        })
        setTimeout(function() {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  // 法务审批同意
  fawuAgree: function() {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否移交给其他法务进行审批',
      confirmText: "是",
      cancelText: '否',
      success: res => {
        var legalStatus = '0'
        if (res.confirm) {
          legalStatus = '1';
        } else {
          legalStatus = '0';
        }
        lwx.request({
          url: "legalStatus.update",
          data: {
            applyVerifyId: that.data.applyVerifyId,
            verifyStatus: 'PASSED',
            useBigissues: that.data.useBigissues,
            legalStatus: legalStatus,
            partyId: _globle.user.partyId,
            companyId: _globle.user.companyId
          }
        }).then(res => {
          console.log(res)
          if (res.data.code == '0') {
            wx.showToast({
              title: '已同意',
            })
            setTimeout(function() {
              wx.navigateBack({
                delta: 1,
              })
            }, 1000)
          } else {
            console.log('错误');
          }
        }).catch(err => {
          console.log('err' + err);
        })
      }
    })
  },

  //重大事项拒绝
  zhongdaRefuse: function() {
    var that = this;
    lwx.request({
      url: "biguess.update",
      data: {
        applyVerifyId: that.data.applyVerifyId,
        verifyStatus: 'REJECT',
        partyId: _globle.user.partyId,
        companyId: _globle.user.companyId
      }
    }).then(res => {
      console.log(res)
      if (res.data.code == '0') {
        wx.showToast({
          title: '已拒绝',
        })
        setTimeout(function() {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  // 重大事项同意
  zhongdaAgree: function() {
    var that = this;
    lwx.request({
      url: "biguess.update",
      data: {
        applyVerifyId: that.data.applyVerifyId,
        verifyStatus: 'PASSED',
        partyId: _globle.user.partyId,
        companyId: _globle.user.companyId
      }
    }).then(res => {
      console.log(res)
      if (res.data.code == '0') {
        wx.showToast({
          title: '已同意',
        })
        setTimeout(function() {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },

  //待批准已批准已撤销
  loadDetail: function(applyId) {
    var that = this;
    lwx.request({
      url: "apply.finddetails.info",
      data: {
        applyId: applyId,
      }
    }).then(res => {
      if (res.data.code == '0') {
        var iwLegalNames = [];
        var processData = [];
        var special = [];
        var bigissueg = [];
        if (res.data.ilegal) {
          iwLegalNames = that.reloadPerson(res.data.ilegal);
        }
        if (res.data.sequence) {
          processData = that.reloadPerson(res.data.sequence);
        }
        if (res.data.special) {
          special = that.reloadPerson(res.data.special);
        }
        if (res.data.bigissueg) {
          bigissueg = that.reloadPerson(res.data.bigissueg);
        }

        var phonePhotoUrls = res.data.applys.handSetFileUrl || [];
        if (phonePhotoUrls.length < 9) {
          phonePhotoUrls.unshift(that.data.applyInfo[0])
        }
        that.setData({
          processData: processData,
          iwLegalNames: iwLegalNames,
          bigissueg: bigissueg,
          special: special,
          detail: res.data.applys,
          applyImageUrl: res.data.upfile.fileurl || [],
          phonePhotoUrls: phonePhotoUrls,
        })
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  //申请详情
  loadData: function(applyId, applyVerifyId) {
    var that = this;
    lwx.request({
      url: "verify.info",
      data: {
        applyId: applyId,
        applyVerifyId: applyVerifyId,
      }
    }).then(res => {
      console.log(res)
      if (res.data.code == '0') {
        var applyImageUrl = [];
        for (var i = 0; i < res.data.iapply.upfileDtos.length; i++) {
          var dic = res.data.iapply.upfileDtos[i];
          applyImageUrl.push(dic.fileUrl)
        }
        console.log(applyImageUrl)
        that.setData({
          detail: res.data.iapply,
          applyImageUrl: applyImageUrl
        })
        if (res.data.iworkflow) {
          that.reloadApplyPeson(res.data.iworkflow.settings);
        }
        if (res.data.iwLegal) {
          that.reloadiwLegalPeson(res.data.iwLegal.name);
        }
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  //已拒绝详情
  loadJujueData: function(applyId) {
    var that = this;
    lwx.request({
      url: "apply.find.info",
      data: {
        applyId: applyId,
      }
    }).then(res => {
      console.log(res)
      if (res.data.code == '0') {
        that.setData({
          detail: res.data.applys,
          applyImageUrl: res.data.upfile.fileurl || []
        })
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  //待核查和已核查
  loadDaihechaData: function(devicesId, status) {
    var that = this;
    lwx.request({
      url: "apply.inspdetails.info",
      data: {
        devicesActId: devicesId,
        censorStatus: status,
      }
    }).then(res => {
      if (res.data.code == '0') {
        var hechaImageUrl = res.data.iApply.fileurl || [];
        if (hechaImageUrl.length < 9) {
          hechaImageUrl.unshift(that.data.applyInfo[0])
        }
        that.setData({
          detail: res.data.devicesAct,
          applyImageUrl: res.data.upfile.fileurl,
          hechaImageUrl: hechaImageUrl
        })
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },

  //拍照上传使用证明
  onUpload: function(e) {
    var that = this;
    if (e.currentTarget.dataset.index == 0) {
      var sourceType = [];
      if (that.data.detail.isForcedPhoto == 'N') {
        sourceType = ['album', 'camera'];
      } else {
        sourceType = ['camera'];
      }
      lwx.chooseImage({
        count: 1,
        sourceType: sourceType
      }).then(res => {
        if (!res.tempFilePaths[0]) {
          throw new Error('未选择图片')
        }
        wx.showLoading({
          title: '图片上传...',
          mask: true
        })
        wx.uploadFile({
          url: _globle.unLoginUrl + 'app/upload' + ".htm",
          filePath: res.tempFilePaths[0],
          name: 'imgFile',
          header: {
            "content-type": "multipart/form-data"
          },
          formData: {
            type: 'xiaochengxu',
          },
          success: function(res) {
            var data = JSON.parse(res.data)
            wx.hideLoading()
            if (data.code == '0') {
              var formData = {
                fileUrl: data.result[0],
                fileType: data.result[data.result.length - 1],
                devicesActId: that.data.detail.devicesActId || that.data.detail.devicesTakeId
              }
              lwx.request({
                url: "handSet.save",
                data: formData
              }).then(res => {
                console.log(res)
                if (res.data.code == '0') {
                  wx.showToast({
                    title: '上传成功',
                    icon: 'none',
                  })
                  that.data.hechaImageUrl.push(data.result[0])
                  that.setData({
                    hechaImageUrl: that.data.hechaImageUrl
                  })
                } else {
                  wx.showToast({
                    title: res.data.message,
                    icon: 'none',
                  })
                }
              }).catch(err => {
                console.log('err' + err);
              })

            } else {
              reject('上传图片失败')
            }
          },
          fail: function(err) {
            wx.hideLoading()
          }
        })
      }).catch(err => {
        console.log(err)
        wx.hideLoading()
      })
    }
    // else {
    //   var array = array.concat(that.data.hechaImageUrl);
    //   array.pop();
    //   wx.previewImage({
    //     current: that.data.hechaImageUrl[e.currentTarget.dataset.index], // 当前显示图片的http链接
    //     urls: hechaImageUrl // 需要预览的图片http链接列表
    //   })
    // }

  },


  //拍照上传
  addPhonePhoto: function(e) {
    if (!this.data.isUsed) {
      wx.showModal({
        title: '提示',
        content: '请先盖章',
        confirmText: "好",
        showCancel: false,
        success: res => {}
      })
    } else {
      var that = this;
      if (e.currentTarget.dataset.index == 0) {
        var sourceType = [];
        if (that.data.detail.isForcedPhoto == 'N') {
          sourceType = ['album', 'camera'];
        } else {
          sourceType = ['camera'];
        }
        lwx.chooseImage({
          count: 1,
          sourceType: sourceType
        }).then(res => {
          if (!res.tempFilePaths[0]) {
            throw new Error('未选择图片')
          }
          wx.showLoading({
            title: '图片上传...',
            mask: true
          })
          wx.uploadFile({
            url: _globle.unLoginUrl + 'app/upload' + ".htm",
            filePath: res.tempFilePaths[0],
            name: 'imgFile',
            header: {
              "content-type": "multipart/form-data"
            },
            formData: {
              type: 'xiaochengxu',
            },
            success: function(res) {
              var data = JSON.parse(res.data)
              wx.hideLoading()
              if (data.code == '0') {
                var formData = {
                  fileUrl: data.result[0],
                  fileType: data.result[data.result.length - 1],
                  devicesActId: that.data.detail.devicesActId || that.data.detail.devicesTakeId
                }
                lwx.request({
                  url: "handSet.save",
                  data: formData
                }).then(res => {
                  console.log(res)
                  if (res.data.code == '0') {
                    wx.showToast({
                      title: '上传成功',
                      icon: 'none',
                    })
                    that.data.phonePhotoUrls.push(data.result[0])
                    that.setData({
                      phonePhotoUrls: that.data.phonePhotoUrls
                    })
                  } else {
                    wx.showToast({
                      title: res.data.message,
                      icon: 'none',
                    })
                  }
                }).catch(err => {
                  console.log('err' + err);
                })

              } else {
                reject('上传图片失败')
              }
            },
            fail: function(err) {
              wx.hideLoading()
            }
          })
        }).catch(err => {
          console.log(err)
          wx.hideLoading()
        })
      } else {
        var array = array.concat(that.data.phonePhotoUrls);
        array.pop();
        wx.previewImage({
          current: that.data.phonePhotoUrls[e.currentTarget.dataset.index], // 当前显示图片的http链接
          urls: array // 需要预览的图片http链接列表
        })
      }
    }
  },

  zoomApplyImageUrl: function(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.pic, // 当前显示图片的http链接
      urls: this.data.applyImageUrl // 需要预览的图片http链接列表
    })
  },
  // processData: [{
  //   name: '李大国',
  //   start: '#fff',
  //   end: '#EFF3F6',
  //   icon: 'red'
  // }],
  //待批准已批准已拒绝lodo状态
  reloadPerson: function(res) {
    var processData = [];
    for (var i = 0; i < res.length; i++) {
      var j = i + 1;
      if (j == res.length) {
        j = i;
      }
      if (res[i].verifyStatus == 'PASSED' && res[j].verifyStatus == 'PASSED') {
        res[i].start = 'red';
        res[i].end = 'red';
        res[i].icon = 'red';
      } else if (res[i].verifyStatus == 'PASSED') {
        res[i].start = 'red';
        res[i].end = '#EFF3F6';
        res[i].icon = 'red';
      } else {
        res[i].start = '#EFF3F6';
        res[i].end = '#EFF3F6';
        res[i].icon = '#eff3f6';
      }
      if (i == res.length - 1) {
        res[i].end = '#fff'
      }
      if (i == 0) {
        res[i].start = '#fff'
      }
      var dic = {
        name: res[i].name,
        start: res[i].start,
        end: res[i].end,
        icon: res[i].icon
      }
      processData.push(dic)
    }
    console.log('processData' + processData)
    return processData;
    // this.setData({
    //   processData: processData
    // })
  },
  reloadApplyPeson: function(res) {
    var processData = [];
    var j = 0;
    for (var i = 0; i < res.length; i++) {
      if (res[i].verifyStatus) {
        j++;
        res[i].person.start = '#fff';
        res[i].person.end = 'red';
        res[i].person.icon = 'red';

      } else {
        res[i].person.start = '#EFF3F6';
        res[i].person.end = '#EFF3F6';
        res[i].person.icon = '#eff3f6';
      }
      if (i == res.length - 1) {
        res[i].person.end = '#fff'
      }
      if (i == 0) {
        res[i].person.start = '#fff'
      }
      var dic = {
        name: res[i].person.name,
        start: res[i].person.start,
        end: res[i].person.end,
        icon: res[i].person.icon
      }
      processData.push(dic)
    }
    this.setData({
      processData: processData
    })
  },
  // 法务审批列表
  reloadiwLegalPeson: function(res) {
    var iwLegalNames = [];
    for (var i = 0; i < res.length; i++) {
      var dic = {};
      dic.start = 'red';
      dic.end = 'red';
      dic.icon = 'red';
      if (i == res.length - 1) {
        dic.end = '#fff'
      }
      if (i == 0) {
        dic.start = '#fff'
      }
      dic.name = res[i];
      iwLegalNames.push(dic)
    }
    this.setData({
      iwLegalNames: iwLegalNames
    })
  },


  apply: function() {
    this.setData({
      hiddenModal: false
    })
  },
  //撤销理由
  input: function(e) {
    this.setData({
      textvalue: e.detail.value
    })
  },
  modalcancel: function() {
    this.setData({
      hiddenModal: true,
      textvalue: ''
    })
  },
  //确定撤销
  modalconfirm: function() {
    var that = this;
    lwx.request({
      url: "apply.type.update",
      data: {
        applyId: this.data.applyId,
        applyStatus: 'RETRACT',
        verifyResult: that.data.textvalue
      }
    }).then(res => {
      if (res.data.code == '0') {
        wx.showToast({
          title: '撤销成功',
        })
        setTimeout(function() {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })

    this.setData({
      hiddenModal: true
    })
  },
  // 保存
  save: function() {
    const _this = this
    const applyInfo = this.data.applyInfo || []
    console.log('applyInfo', applyInfo)
    const iupfile = []
    for (var i = 0; i < applyInfo.length; i++) {
      if (i != 0) {
        iupfile.push({
          fileUrl: applyInfo[i],
          fileType: 'jpeg'
        })
      }
    }
    console.log('iupfile--', iupfile)
    const data = {
      applyId: _this.data.detail.applyId,
      iupfile: iupfile
    }
    lwx.request({
      url: "upfile.save",
      data: data
    }).then(res => {
      console.log(res)
      if (res.data.code == '0') {
        wx.showToast({
          title: '提交成功',
          icon: 'none',
        })
        setTimeout(function() {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      } else {
        console.log('错误');
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  use: function() {
    var that = this
    if (!that._devices) {
      that._devices = new devices(that.data.detail.devicesCode)
    }
    let errMsg = '使用失败'
    that._devices.getOperationStatus().then(res => {
      return new Promise((resolve, reject) => {
        console.log(res)
        if (res.operationStatus === 0) {
          that.rand1 = res.rand1
          that.rand2 = res.rand2
          resolve(res.operationStatus)
        } else if (res.operationStatus === 1) {
          reject('设备繁忙,请稍后再试')
        } else {
          resolve(res.operationStatus)
          reject('设备已锁定，请先到设备详情解锁')
        }
      })
    }).then(res => {
      wx.hideLoading()
      wx.showLoading({
        title: '使用印章',
        mask: true
      })
      return lwx.request({
        url: 'use.useSeal',
        data: {
          id: that.data.detail.devicesActId || that.data.detail.devicesTakeId,
          partyId: _globle.user.partyId,
          type: that.data.detail.applyType,
          devicesId: that.data.detail.devicesId
        }
      })
    }).then(res => {
      that._usedId = res.data.useId
      console.log('useId======' + res.data.useId)
      wx.hideLoading()
      wx.showLoading({
        title: '解锁设备...',
        mask: true
      })
      // 解锁设备
      return that._devices.setOperationCommand({
        type: 2,
        sign: that.data.detail.sign,
        rand1: that.rand1,
        rand2: that.rand2
      })
    }).then(res => {
      return new Promise((resolve, reject) => {
        console.log('进入获取状态')
        let devicesStatus = 0
        let msg = '获取状态...'
        wx.hideLoading()
        wx.showLoading({
          title: msg,
          mask: true
        })
        let handler = () => {
          this._devices.getOperationStatus().then(res => {
            console.log('要敲章了=====' + JSON.stringify(res))
            if (res.operationStatus == 1) {
              if (res.devicesStatus != devicesStatus) {
                devicesStatus = res.devicesStatus
                console.log('devicesStatus' + devicesStatus)
                this.setData({
                  isUsed: true
                })
                switch (devicesStatus) {
                  case 2:
                    msg = '正在敲章';
                    break
                  case 11:
                    msg = '印章已按下';
                    break
                  case 12:
                    msg = '印章已返回';
                    break
                }
                wx.hideLoading()
                wx.showLoading({
                  title: msg,
                  mask: true
                })
              }
              setTimeout(handler, 100)
            } else {
              resolve(res.operationStatus)
            }
          })
        }
        setTimeout(handler, 100)
      })
    }).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res === 0) {
        this.useSuccess()
      } else {
        this.useError()
      }
    }).catch(err => {
      console.log(err)
      errMsg = typeof err === 'string' ? err : errMsg
      wx.showToast({
        title: errMsg,
        mask: true,
        icon: 'none'
      })
    })
  },
  useSuccess: function() {
    setTimeout(function() {
      wx.showToast({
        title: '用章完成',
        mask: true
      })
    }, 1000)

    // this.nextStep()
  },
  useError: function() {
    if (!this._devices) {
      this._devices = new devices(this._deviceCode)
    }
    this._devices.getErrorInfo().then(res => {

      let times = null
      if (res.errorType == 4) {
        times = res.errorData
      }
      let errMsg = res.mes
      // lwx.request({
      //   url: '/use/rollback',
      //   data: {
      //     actId: this._actId,
      //     latitude: _globle.location.latitude || '',
      //     longitude: _globle.location.longitude || '',
      //     cause: errMsg ? errMsg : '其他原因',
      //     times: times || ''
      //   }
      // }).then(res => {
      //   console.log('记录使用失败成功')
      // }).catch(err => {
      //   console.log('记录使用失败失败')
      // })

      wx.showModal({
        title: '使用失败',
        content: (errMsg ? ('使用失败【' + errMsg + '】') : '') + '设备锁定' + ',解锁设备?',
        cancelText: '取消',
        confirmText: '解锁',
        success: res => {
          if (res.confirm) {
            this.releaseError()
          } else {
            wx.showToast({
              title: '请到设备详情解锁设备才能继续使用',
              mask: true,
              icon: 'none'
            })
          }
        }
      })
    }).catch(err => {
      wx.showModal({
        title: '使用失败',
        content: '使用失败【原因未知】设备锁定,解锁设备?',
        cancelText: '取消',
        confirmText: '解锁',
        success: res => {
          if (res.confirm) {
            this.releaseError()
          } else {
            wx.showToast({
              title: '请到设备详情解锁设备才能继续使用',
              mask: true,
              icon: 'none'
            })
          }
        }
      })
    })
  },
  releaseError: function() {
    if (!this._devices) {
      this._devices = new devices(this.data.detail.devicesCode)
    }
    wx.hideLoading()
    wx.showLoading({
      title: '读取状态...',
      mask: true
    })
    this._devices.getOperationStatus().then(res => {
      if (res.operationStatus === 2) {
        wx.hideLoading()
        wx.showLoading({
          title: '解除锁定',
          mask: true
        })
        this._devices.setOperationCommand({
          type: 3,
          sign: this.data.detail.sign,
          rand1: res.rand1,
          rand2: res.rand2
        }).then(res => {
          return new Promise((resolve, reject) => {
            wx.hideLoading()
            wx.showLoading({
              title: '获取结果...',
              mask: true
            })
            // 循环读取状态
            let statusInterval = setInterval(() => {
              this._devices.getOperationStatus().then(res => {
                // 空闲则是安装完成
                if (res.operationStatus !== 1) {
                  clearInterval(statusInterval)
                  resolve(res.operationStatus)
                }
              })
            }, 100)
          })
        }).then(res => {
          wx.hideLoading()
          if (res === 2) {
            wx.showToast({
              title: '解除错误锁定失败',
              mask: true,
              icon: 'none'
            })
          } else {
            wx.showToast({
              title: '解除成功',
              mask: true
            })
            // this.nextStep()
          }
        }).catch(err => {
          console.log(err)
          wx.hideLoading()
          wx.showToast({
            title: '解除操作失败',
            mask: true,
            icon: 'none'
          })
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '设备正常，无错误信息',
          mask: true,
          icon: 'none'
        })
      }
    }).catch(res => {
      wx.hideLoading()
      wx.showToast({
        title: '获取运行状态失败',
        mask: true,
        icon: 'none'
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    if (this._devices) {
      this._devices.closeConnection()
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})